from datetime import date, datetime
import json
import copy
from urllib import parse

from django.utils.http import urlquote
from django.conf import settings
from rest_framework import serializers
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.settings import api_settings

from apps.common.account.models import Account
from .models import CompanySelfAssessment, FileTemplate, Answer
from apps.pollution.utils import upload_file_to_oss

file_domain = settings.FILE_DOMAIN


class CompanySelfAssCheck(serializers.ModelSerializer):

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.check_people = self.context['request'].user
        instance.check_time = datetime.now()
        instance.save()
        return instance

    class Meta:
        model = CompanySelfAssessment
        fields = ['check_status', 'check_opinion']


class CompanySelfAssessmentSerializer(serializers.ModelSerializer):
    created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    updated_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    check_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    change_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        if instance.check_status == 2:  # 如果之前检查状态是需要修改，则改为已修改
            instance.check_status = 3
        instance.change_time = datetime.now()
        instance.save()
        return instance

    def to_representation(self, instance):
        ret = super().to_representation(instance)

        ret['self_assessment_table_f'] = []
        for i in instance.self_assessment_table:
            file_name = ''.join(i.split('/')[1:])
            url = f"{file_domain}{parse.quote(i)}"
            ret['self_assessment_table_f'].append({'name': file_name, 'url': url})

        # 新增了题目，前端要加上
        if 'category_3_2' not in ret['category_3']:
            ret['category_3']['category_3_2'] = []
        if 'category_3_3' not in ret['category_3']:
            ret['category_3']['category_3_3'] = []
        if 'category_3_4' not in ret['category_3']:
            ret['category_3']['category_3_4'] = []
        if 'category_4_7' not in ret['category_4']:
            ret['category_4']['category_4_7'] = []

        for num in range(1, 9):
            ret[f'category_{num}_f'] = {}
            for k, v in ret[f"category_{num}"].items():
                ret[f'category_{num}_f'][k] = []
                for i in v:
                    file_name = ''.join(i.split('/')[1:])
                    # url = f"{file_domain}{i}"
                    url = f"{file_domain}{parse.quote(i)}"
                    ret[f'category_{num}_f'][k].append({'name': file_name, 'url': url})

        ret['check_people_name'] = ''
        if instance.check_people:
            ret['check_people_name'] = instance.check_people.realname

        return ret

    class Meta:
        model = CompanySelfAssessment
        fields = "__all__"
        read_only_fields = ['id']


class FileTemplateSerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        url = f"{file_domain}template/{instance.name}"
        ret['url'] = url
        return ret

    class Meta:
        model = FileTemplate
        fields = "__all__"


class AnswerSerializer(serializers.ModelSerializer):
    created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['images_full_path'] = []
        ret['images_full_path_f'] = []
        if instance.images:
            for i in instance.images:
                file_name = ''.join(i.split('/')[1:])
                url = f"{file_domain}{i}"
                ret['images_full_path'].append(url)
                ret['images_full_path_f'].append({'name': file_name, 'url': url})
        return ret

    class Meta:
        model = Answer
        fields = '__all__'

